/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.model.command;

import static com.cea.papyrus.diagram.sequence.sedi.model.util.ModelUtil.getFragments;

import org.eclipse.gef.commands.Command;
import org.eclipse.uml2.uml.Interaction;
import org.eclipse.uml2.uml.InteractionFragment;
import org.eclipse.uml2.uml.InteractionOperand;

/**
 * Command to set the owner of an InteractionFragment. The owner is either an
 * Interaction or an InteractionOperand.
 * 
 * <p>
 * The following attributes must be set for the command to complete
 * successfully:
 * </p>
 * <ul>
 * <li>Fragment
 * <li>Owner
 * </ul>
 * 
 * @author frankd@ifi.uio.no
 */
public class SetOwnerCommand extends Command {
	private InteractionFragment fragment;
	private InteractionFragment owner, oldOwner;

	public void setFragment(final InteractionFragment fragment) {
		this.fragment = fragment;
	}

	public void setOwner(final InteractionFragment owner) {
		this.owner = owner;
	}

	@Override
	public void execute() {
		oldOwner = (InteractionFragment) fragment.getOwner();
		doSetOwner(owner);
	}

	@Override
	public void undo() {
		doSetOwner(oldOwner);
		oldOwner = null;
	}

	@Override
	public void redo() {
		this.execute();
	}

	private void doSetOwner(InteractionFragment owner) {
		if (owner instanceof Interaction)
			getFragments((Interaction) owner).add(fragment);
		else
			getFragments((InteractionOperand) owner).add(fragment);
	}

	@Override
	public void dispose() {
		fragment = null;
		owner = null;
	}
}
